using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Xml;
using Domain.Entities;
using Domain.Permissions;
using Domain.Services;
using Domain.Misc;

namespace UserInterface.RSS
{
    public partial class ViewForum : RSSPageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/xml";
            short forumId = Convert.ToInt16(Request.QueryString["forumId"]);
            Forum forum = ForumService.GetById(forumId);
            ForumPermissionManager forumPermissionManager = PermissionManager.CreateForumPermissionManager(forum);

            XmlTextWriter xmlTextwriter = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);
            xmlTextwriter.WriteStartDocument();

            // <rss>
            xmlTextwriter.WriteStartElement("rss");
            xmlTextwriter.WriteAttributeString("version", "2.0");

            // <channel>
            xmlTextwriter.WriteStartElement("channel");
            if (forum != null)
            {
                xmlTextwriter.WriteElementString("title", BoardSettingsManager.Instance.Settings.BoardName + " : " + forum.Name);
            }
            else
            {
                xmlTextwriter.WriteElementString("title", BoardSettingsManager.Instance.Settings.BoardName);
            }
            xmlTextwriter.WriteElementString("link", "http://" + Request.ServerVariables["HTTP_HOST"] + "/Index.aspx");
            xmlTextwriter.WriteElementString("description", "View Forum RSS");
            xmlTextwriter.WriteElementString("copyright", "Madboard. All rights reserved.");

            if (forumPermissionManager.Read)
            {
                // <item>'s
                IList<Topic> topics = TopicService.GetTopicsByForum(forum);
                foreach (Topic topic in topics)
                {
                    // <item>
                    xmlTextwriter.WriteStartElement("item");
                    xmlTextwriter.WriteElementString("title", topic.Subject);
                    xmlTextwriter.WriteElementString("description", "Number of replies:" + topic.NumberOfReplies + " Last reply at: " + topic.LastMessage.PostDateTime);
                    xmlTextwriter.WriteElementString("link", "http://" + Request.ServerVariables["HTTP_HOST"] + "/ViewTopic.aspx?forumId=" + topic.Id);
                    xmlTextwriter.WriteElementString("pubDate", topic.PostDateTime.ToString("R"));
                    xmlTextwriter.WriteEndElement();
                }
            }

            // </channel>
            xmlTextwriter.WriteEndElement();

            // </rss>
            xmlTextwriter.WriteEndElement();

            xmlTextwriter.WriteEndDocument();
            xmlTextwriter.Flush();
            xmlTextwriter.Close();
        }
    }


}
